<template>
  <div class="container-view">

    <!-- header -->
    <div class="container-view-header">
      <!-- 标题 -->
      <h1 class="text-2xl font-bold">文章管理</h1>

      <!-- 操作栏 -->
      <div class="flex flex-wrap justify-between items-center">
        <div class="flex flex-wrap gap-4">
          <FormKit
            type="text"
            name="search"
            placeholder="搜索文章..."
            v-model="searchQuery"
            outer-class="!mb-0"
            input-class="w-full"
            prefix-icon="search"
            help="暂未开发"
          />
          <FormKit
            type="select"
            name="status"
            placeholder="状态筛选"
            :options="statusOptions"
            v-model="statusFilter"
            outer-class="mb-0"
            help="暂未开发"
          />
        </div>
        <FormKit
          type="button"
          @click="openCreateDialog"
          prefix-icon="plus"
          :classes="{
            outer: 'fit-content max-w-fit',
            input: 'bg-primary-600 hover:bg-primary-700 px-4 py-2 rounded',
          }"
        >
          新建文章
        </FormKit>
      </div>
    </div>


    <!-- 文章列表 -->
    <div class="container-view-main">
      <div class="relative overflow-x-auto overflow-y-hidden">
        <table>
          <thead>
            <tr>
              <th>
                标题
              </th>
              <th>
                作者
              </th>
              <th>
                状态
              </th>
              <th>
                发布时间
              </th>
              <th>
                操作
              </th>
            </tr>
          </thead>
          <tbody>
            <tr
              class="hover"
              v-for="(item, index) in articles" :key="item.id"
            >
              <td class="">
                <a
                  :href="`/pages/article.html?id=${item.id}`"
                  target="_blank"
                  rel="noopener noreferrer"
                  class="text-primary-600 hover:text-primary-800 hover:underline cursor-pointer"
                >
                  {{ item.title }}
                </a>
              </td>
              <td>
                {{ item.author }}
              </td>
              <td>
                <span
                  :class="[
                    'px-2 py-1 text-xs rounded-full',
                    getArticleStatus(item) === '已发布'
                      ? 'bg-green-100 text-green-800'
                      : 'bg-yellow-100 text-yellow-800',
                  ]"
                >
                  {{ getArticleStatus(item) }}
                </span>
              </td>
              <td>
                {{ formatDate(item.publish_time) }}
              </td>
              <td>
                <!-- 下拉菜单 -->
                <DaisyDropdown
                  :options="['编辑', '删除']"
                  @select="selectArticleOprationMenuItem($event, index)"
                  :top="index === pageSize - 1 ? true : false"
                  :end="true"
                >
                  <template #label>
                    <svg
                      xmlns="http://www.w3.org/2000/svg"
                      fill="none"
                      viewBox="0 0 24 24"
                      class="inline-block h-5 w-5 stroke-current"
                    >
                      <path
                        stroke-linecap="round"
                        stroke-linejoin="round"
                        stroke-width="2"
                        d="M5 12h.01M12 12h.01M19 12h.01M6 12a1 1 0 11-2 0 1 1 0 012 0zm7 0a1 1 0 11-2 0 1 1 0 012 0zm7 0a1 1 0 11-2 0 1 1 0 012 0z"
                      ></path>
                    </svg>
                  </template>
                </DaisyDropdown>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>

    <!-- footer -->
    <div class="container-view-footer">
      <div class="text-sm text-base-content/80">
        共 {{ articleCount }} 条记录
      </div>
      <div class="flex flex-wrap gap-2">
        <FormKit
          type="button"
          :disabled="currentPage === 1 || loading"
          @click="currentPage--"
          prefix-icon="arrow-left"
          :classes="{
            outer: '!mb-0',
            input: 'px-3 py-1 rounded border',
            disabled: 'opacity-50 cursor-not-allowed',
          }"
        >
          上一页
        </FormKit>
        <FormKit
          type="button"
          :disabled="currentPage === pageCount || loading"
          @click="currentPage++"
          suffix-icon="arrow-right"
          :classes="{
            outer: '!mb-0',
            input: 'px-3 py-1 rounded border',
            disabled: 'opacity-50 cursor-not-allowed',
          }"
        >
          下一页
        </FormKit>
      </div>
    </div>

    <!-- 创建/编辑对话框 -->
    <DaisyDialog
      ref="articleDialog"
      :title="dialogMode === 'create' ? '创建文章' : '编辑文章'"
      :close-button="true"
      :large="true"
      @close="handleDialogClose"
    >
      <FormKit
        id="form-article"
        type="form"
        :actions="false"
        @submit="handleSave"
      >
        <FormKit
          type="url"
          name="cover"
          label="封面图片"
          :validation="[
            [
              'matches',
              /((^\/resource\/images\/[^\/\?&=]+\.(jpg|jpeg|png|gif|webp|bmp)$)|(^https?:\/\/[^\?&=]+\.(jpg|jpeg|png|gif|webp|bmp))$)/i,
            ],
          ]"
          validation-label="封面图片"
          v-model="formData.cover"
          :validation-messages="{
            matches: '请输入有效的图片URL',
          }"
          outer-class="max-w-full"
        />

        <FormKit
          type="text"
          name="title"
          label="标题"
          validation="required"
          validation-label="标题"
          v-model="formData.title"
          :validation-messages="{
            required: '请输入标题',
          }"
          outer-class="max-w-full"
        />

        <FormKit
          type="date"
          name="date"
          label="日期"
          validation="required"
          validation-label="日期"
          v-model="formData.date"
          :validation-messages="{
            required: '请选择日期',
          }"
          outer-class="max-w-full"
        />

        <FormKit
          type="select"
          name="sort"
          label="分类"
          validation="required"
          :options="
            Object.fromEntries(articleSorts.map((item) => [item.id, item.name]))
          "
          v-model="formData.sort_id"
          outer-class="max-w-full"
        />

        <FormKit
          type="text"
          name="author"
          label="作者"
          validation-label="作者"
          v-model="formData.author"
          :validation-messages="{
            required: '请输入作者',
          }"
          outer-class="max-w-full"
        />

        <FormKit
          type="url"
          name="author_home_page"
          label="作者主页"
          validation="url"
          validation-label="作者主页"
          v-model="formData.author_home_page"
          :validation-messages="{
            url: '请输入有效的URL',
          }"
          outer-class="max-w-full"
        />

        <FormKit
          type="textarea"
          name="content"
          label="内容"
          validation="required"
          validation-label="内容"
          v-model="formData.content"
          :validation-messages="{
            required: '请输入文章内容',
          }"
          :classes="{
            outer: 'min-w-full',
            wrapper: 'w-full',
            input: 'w-full h-64',
          }"
        />
      </FormKit>

      <template #footer>
        <div class="flex justify-end gap-4">
          <button class="btn btn-ghost" @click="closeDialog">取消</button>
          <button
            class="btn btn-primary"
            :class="{ loading: saving }"
            :disabled="saving"
            @click="clickSaveArticleButton"
          >
            {{ saving ? "保存中..." : "保存" }}
          </button>
        </div>
      </template>
    </DaisyDialog>
  </div>
</template>

<script setup lang="ts">
import DaisyDropdown from "@/components/daisy-dropdown/DaisyDropdown.vue";
import type { DaisyDropdownSelectArgument } from "@/components/daisy-dropdown/DaisyDropdown.vue";
import DaisyDialog from "@/components/daisy-dialog/DaisyDialog.vue";
import { FormKit } from "@formkit/vue";
import { ref, onMounted, watch } from "vue";
import articleAPI from "@/api/article";
import type { Article } from "@/api/article";
import { ResponseCode } from "@/api/request";
import { formatDateYYYYMMDD, formatDate } from "@/util/formater";
import { useDaisyLoading } from "@/components/daisy-loading/daisy.loading";
const daisyLoading = useDaisyLoading();

// HTMLElements
let articleForm: HTMLElement | null = null;

// 状态项
const statusOptions = {
  all: "全部",
  published: "已发布",
  draft: "草稿",
} as const;
type StatusFilterType = keyof typeof statusOptions;

// 数据状态
const loading = ref(false);
const saving = ref(false);
const searchQuery = ref("");
const statusFilter = ref<StatusFilterType>("all");
const currentPage = ref(1);
const pageCount = ref(1);
const articleCount = ref(0);
const articles = ref<Article[]>([]);
const articleSorts = ref<{ id: number; name: string; description: string }[]>(
  [],
);
const pageSize = 10; // 每页显示数量

// 修改对话框相关的状态管理
const articleDialog = ref<InstanceType<typeof DaisyDialog> | null>(null);
const dialogMode = ref<"create" | "edit">("create");
const editingArticle = ref<Article | null>(null);

// 修改表单数据的类型定义
interface FormData {
  cover: string | undefined;
  title: string;
  date: string;
  sort_id: number;
  publisher_id: number;
  author: string | undefined;
  author_home_page: string | undefined;
  content: string;
}

// 表单数据初始值
const formData = ref<FormData>({
  cover: "",
  title: "",
  date: formatDateYYYYMMDD(new Date()),
  sort_id: 1,
  publisher_id: 1, // 这里需要从用户状态获取
  author: undefined,
  author_home_page: undefined,
  content: "",
});

// 重置表单
const resetForm = () => {
  formData.value = {
    cover: undefined,
    title: "",
    date: formatDateYYYYMMDD(new Date()),
    sort_id: 1,
    publisher_id: 1,
    author: undefined,
    author_home_page: undefined,
    content: "",
  };
};

// 修改模板中的状态显示
const getArticleStatus = (article: Article): string => {
  const now = new Date();
  const publishTime = new Date(article.publish_time);
  return publishTime <= now ? "已发布" : "待发布";
};

const fetchArticleSorts = async () => {
  const result = await articleAPI.getArticleAllSort();
  if (result.code === ResponseCode.SUCCESS) {
    articleSorts.value = result.data;
  }
};

// 获取文章列表
const fetchArticles = async () => {
  loading.value = true;
  try {
    articleCount.value = (await articleAPI.getArticleCount()).data || 0;

    // searchPage
    if (searchQuery.value) {
      console.log("搜索", searchQuery.value);
    }
    // getPage
    else {
      const result = await articleAPI.getArticlePage(
        currentPage.value,
        pageSize,
        true,
      );
      if (result.code === ResponseCode.SUCCESS) {
        articles.value = result.data;
        pageCount.value = Math.ceil(articleCount.value / pageSize);
      }
    }
    if (statusFilter.value !== "all") {
      console.log("筛选", statusFilter.value);
    }
  } catch (error) {
    console.error("获取文章列表失败:", error);
  } finally {
    loading.value = false;
  }
};

// 监听分页和筛选变化
watch([currentPage, statusFilter, searchQuery], () => {
  fetchArticles();
});
// 监听加载状态
watch(loading, (nv) => {
  if (nv) {
    daisyLoading.showLoading();
  } else {
    daisyLoading.hideLoading();
  }
});

// 打开创建对话框
const openCreateDialog = () => {
  dialogMode.value = "create";
  resetForm();
  articleDialog.value?.show();
};

// 点击文章操作下拉菜单
const selectArticleOprationMenuItem = (
  arg: DaisyDropdownSelectArgument<string>,
  articleIndex: number,
) => {
  const itemIndex = arg.index;
  const article = articles.value[articleIndex];
  if (itemIndex === 0) {
    editArticle(article);
  } else if (itemIndex === 1) {
    deleteArticle(article.id);
  }
};

// 打开编辑对话框
const editArticle = (article: Article) => {
  dialogMode.value = "edit";
  editingArticle.value = article;
  formData.value = {
    cover: article.cover,
    title: article.title,
    date: formatDateYYYYMMDD(new Date(article.date)),
    sort_id: article.sort_id,
    publisher_id: article.publisher_id,
    author: article.author,
    author_home_page: article.author_home_page,
    content: article.contentData?.content?.toString() || article.content || "",
  };
  articleDialog.value?.show();
};

// 点击保存
const clickSaveArticleButton = () => {
  // 触发提交事件
  const submitEvent = new SubmitEvent("submit");
  articleForm?.dispatchEvent(submitEvent);
};

// 提交
const handleSave = async () => {
  if (saving.value) return;

  saving.value = true;
  try {
    const dto: any = {
      ...formData.value,
      date: new Date(formData.value.date),
      content_type: "markdown",
    };

    if (dialogMode.value === "create") {
      const result = await articleAPI.createArticle(dto);
      if (result.code === ResponseCode.SUCCESS) {
        await fetchArticles();
        articleDialog.value?.hide();
      }
    } else {
      const result = await articleAPI.updateArticle(
        editingArticle.value!.id,
        dto,
      );
      if (result.code === ResponseCode.SUCCESS) {
        await fetchArticles();
        articleDialog.value?.hide();
      }
    }
  } catch (error) {
    console.error("保存文章失败:", error);
  } finally {
    saving.value = false;
  }
};

// 删除文章
const deleteArticle = async (id: number) => {
  if (confirm("确定要删除这篇文章吗？")) {
    try {
      const result = await articleAPI.deleteArticle(id);
      if (result.code === ResponseCode.SUCCESS) {
        fetchArticles();
      }
    } catch (error) {
      console.error("删除文章失败:", error);
    }
  }
};

// 关闭对话框
const closeDialog = () => {
  articleDialog.value?.close();
};
// 处理对话框关闭事件
const handleDialogClose = () => {
  resetForm();
  editingArticle.value = null;
};

onMounted(async () => {
  articleForm = document.getElementById("form-article");
  await fetchArticleSorts();
  await fetchArticles();
});
</script>
